package com.ladlee.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ladlee.model.SysMenu;
import com.ladlee.model.SysRole;
import com.ladlee.model.SysUser;
import com.ladlee.system.dao.UserMapper;
import com.ladlee.system.service.MenuService;
import com.ladlee.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: dingchang
 * @Date: 2018/12/22 16:59
 * @Description:
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService, UserDetailsService {

    @Autowired
    MenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("【UserServiceImpl】 loadUserByUsername 表单登录用户名  username={}", username);
        List<GrantedAuthority> authorities = new ArrayList();
        SysUser user = this.baseMapper.loadUserByUser(username);
        if (user != null) {
            //拥有的角色
            List<SysRole> roleList = user.getRoleList();
            for (SysRole r : roleList){
                if(StringUtils.isNotBlank(r.getRoleName())){
                    //权限如果前缀是ROLE_，security就会认为这是个角色信息，而不是权限，例如ROLE_MENBER就是MENBER角色，CAN_SEND就是CAN_SEND权限
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + r.getRoleName()));
                }
            }
            //拥有的菜单
            List<SysMenu> menus = sysMenuService.getPermissions(user.getUsername());
            for (SysMenu m : menus){
                if(StringUtils.isNotBlank(m.getPermission())){
                    authorities.add(new SimpleGrantedAuthority(m.getPermission()));
                }
            }
            log.info("权限集合为:{}",authorities);
            return new SysUser(user.getUsername(), user.getPassword(), authorities);
        }else{
            throw new BadCredentialsException("用户名不存在！");
        }
    }
}
